"""
    Module with agreement defenition and accompanying classes.
"""

from sqlobject import DatabaseIndex
from sqlobject.col import UnicodeCol, ForeignKey, IntCol, DateCol, BoolCol
from mnemoply.model.model_object import ModelObject
from mnemoply.model.columns import TariffCol, CurrencyCol, PhoneCol
from mnemoply.model import constants
from mnemoply.utils import format_currency
from mnemoply.model.hub import __connection__
from datetime import date

class Customer(ModelObject):
    """
        More often this instance is student parent.
    """

    model_title = _("Customer")

    surname = UnicodeCol(length=80, default='', notNull=True, title=_("Surname"))
    forename = UnicodeCol(length=80, default='', notNull=True, title=_("Forename"))
    patronymic = UnicodeCol(length=80, default='', notNull=True, title=_("Patronymic"))
    phone = UnicodeCol(length=100, default='', notNull=True, title=_("Phone"))
    phone_main = PhoneCol( default='',  title=_("Main phone"))
    phones_more = UnicodeCol(length=30, default='', title=_("More phones"))
    email = UnicodeCol(length=140, default='', notNull=True, title=_("E-mail"))

    title = property(lambda self: "%s %s %s" % (self.surname, self.forename, self.patronymic))

class CustomerTariff(ModelObject):
    """
        Tariff for customer.
    """

    model_title = _("Customer tariff")

    isShort = BoolCol(notNull=True, default=False, title=_("Short"))
    tariff = TariffCol(notNull=True, title=_("Tariff"))
    agreementCost = CurrencyCol(notNull=True, title=_("Agreement cost"))
    prepaymentCost = CurrencyCol(notNull=True, title=_("Prepayment cost"))

    def getName(self):
        if self.isShort:
            return "%d " % self.agreementCost + _("rub.") + _(" per month")
        return "%d/%d " % (self.tariff[8], self.tariff[0]) + _("rub.") + _(" per hour")

    title = property(lambda self: self.getName())


class CustomerTariffPlan(ModelObject):
    """
        M2M between CustomerTariff and Plan.
    """

    model_title = _("Customer tariff plan")

    plan = ForeignKey('Plan', notNull=True, title=_("Plan"))
    customerTariff = ForeignKey('CustomerTariff', notNull=True, title=_("Customer tariff"))

    title = property(lambda self: "%s %s" % (self.plan.title, self.customerTariff.title))


class QuantityAddition(ModelObject):
    """
        Teachers salary addition for the quantity of students.
    """

    model_title = _("Quantity addition")

    addition = CurrencyCol(notNull=True, title=_("Addition"), default=0)
    numStudents = IntCol(notNull=True, title=_("Number of students"), default=0)
    uniqueAddition = DatabaseIndex('addition', 'numStudents', unique=True)

    title = property(lambda self: "%s - %s" % (self.numStudents, format_currency(self.addition)))


class QuantityAdditionTeacherTariff(ModelObject):
    """
        M2M between TeacherTariff and QuantityAddition.
    """

    model_title = _("QuantityAddition-TeacherTariff")

    tariff = ForeignKey('TeacherTariff', notNull=True, title=_("Teacher tariff"))
    addition = ForeignKey('QuantityAddition', notNull=True, title=_("Quantity addition"))
    uniqueAddition = DatabaseIndex('tariff', 'addition', unique=True)

    title = property(lambda self: "%s %s" % (self.tariff.title, self.addition.title))


class EducationInfo(ModelObject):
    """
        Addition to agreement.
    """

    model_title = _("Education info")

    possibleDay = UnicodeCol(length=80, default='', notNull=True, title=_("Possible day"))
    unpossibleDay = UnicodeCol(length=80, default='', notNull=True, title=_("Unpossible day"))
    office = ForeignKey('Office', default=None, title=_("Office"))

    friends = UnicodeCol(length=200, default='', notNull=True, title=_("Friends"))
    comment = UnicodeCol(default='', notNull=True, title=_("Comment"))

    testResultBasic = IntCol(default=None, title=_("Basic test result"))
    testResultProf = UnicodeCol(length=80, default='', notNull=True, title=_("Prof. test result"))

    studentAgreement = ForeignKey("StudentAgreement", notNull=True, title=_("Student agreement"))

    title = property(lambda self: self.studentAgreement.title)


class StudentAgreement(ModelObject):
    """
        A document, reason for pay and charge money to student balance.
    """

    model_title = _("Student agreement")

    contract = ForeignKey('Contract',  default=0, title=_("Contract"))
    student = ForeignKey('Student', notNull=True, title=_("Student"))
    customer = ForeignKey('Customer', notNull=True, title=_("Customer"))

    year = IntCol(notNull=True, title=_("Year"), default=constants.getAcademicYear)

    agreementType = ForeignKey('AgreementType', notNull=True, title=_("Education type"), default=1)

    organization = ForeignKey('Organization', notNull=True, title=_("Organization"))
    customerTariff = ForeignKey('CustomerTariff', notNull=True, title=_("Customer tariff"))
    trend = ForeignKey('Trend', notNull=True, title=_("Trend"))
    informationSource = ForeignKey('InformationSource', default=None, title=_('Information source'))
    event = ForeignKey('Event', default=None, title=_('Event'))

    initialPlan = ForeignKey('Plan', default=None, title=_("Initial plan"))
    initialPlanStudentWish = ForeignKey('Plan', default=None, title=_("Initial plan student wish"))

    dateEnterAgreement = DateCol(notNull=True, title=_("Date enter agreement"))
    dateBeginAgreement = DateCol(notNull=True, default=lambda: date.today(), title=_("Date begin agreement"))
    dateEndAgreement = DateCol(notNull=True, default=lambda: date.today(), title=_("Date end agreement"))
    dateCancellationAgreement = DateCol(notNull=False, default=None, title=_("Date cancellation agreement"))

    dateLastCoupon = DateCol(notNull=False, default=None, title=_("Date of last coupon"))

    countPrint = IntCol(notNull=True, title=_("Count print"), default=0)
    ordinal = IntCol(notNull=True, title=_("Ordinal"), default=0)

    def getPlan(self):
        if self.initialPlan is None:
            return self.initialPlanStudentWish
        return self.initialPlan

    def getPlanTitle(self):
        if self.getPlan() is not None:
            return self.getPlan().title
        return _("*No plan*")

    title = property(lambda self: "%s %s %s" %
        (self.student.title, self.dateBeginAgreement.strftime("%d.%m.%Y"), self.getPlanTitle()))


class Contract(ModelObject):
    

    model_title = _("Contract")

    student = ForeignKey('Student', notNull=True, title=_("Student"))
    customer = ForeignKey('Customer', notNull=True, title=_("Customer"))
    organization = ForeignKey('Organization', notNull=True, title=_("Organization"))
    countPrint = IntCol(notNull=True, title=_("Count print"), default=0)

    title = property(lambda self: "%s %s " %
        (self.student.title, self.organization.title))

    def getAgreementList(self):
        return StudentAgreement.selectBy(student=self.student,customer=self.customer,organization=self.organization)


